package top.yangyitao.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.UnauthenticatedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import top.yangyitao.dto.ResultDto;

@Controller
public class ExceptionController implements HandlerExceptionResolver {
	
	private static final Logger LOG = LoggerFactory.getLogger(ExceptionController.class);
	
	@Autowired
	ObjectMapper objectMapper;
	
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception e) {
		LOG.error(e.getMessage(),e);
		if(e instanceof UnauthenticatedException) {
			try {
			ResultDto resultDto = new ResultDto("尚未登录或登陆已过期，请刷新页面",null,2);
			response.setCharacterEncoding("UTF-8");  
		    response.setContentType("application/json; charset=utf-8");
		    PrintWriter out = response.getWriter();
			objectMapper.writeValue(out, resultDto);
		    out.flush();
		    out.close();
		    return null;
			} catch (JsonGenerationException e1) {
				LOG.error(e1.getMessage(),e1);
			} catch (JsonMappingException e1) {
				LOG.error(e1.getMessage(),e1);
			} catch (IOException e1) {
				LOG.error(e1.getMessage(),e1);
			}
		}
		ModelAndView mv = new ModelAndView();
		mv.addObject("message", "服务器崩了呢(~~),异常信息:"+e.getMessage());
		mv.setViewName("/error.html");
		mv.setStatus(HttpStatus.INTERNAL_SERVER_ERROR);
		return mv;
	}

}
